package com.smart.translate.handler;

import com.smart.translate.annotation.SmartTranslateAnnotation;
import com.smart.translate.annotation.SmartTranslateItemAnnotation;
import com.smart.translate.config.SmartTranslateConfig;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @ClassName DefaultSmartTranslateHandler
 * @Description TODO
 * @Author YY
 * @create: 2025−08-20 17:08
 */
@Component
public class DefaultSmartTranslateHandler implements SmartTranslateHandler {

    @Override
    public Object translate(Object rawValue, SmartTranslateAnnotation annotation, Object target) {

        for (SmartTranslateItemAnnotation item : annotation.items()) {
            //获取指定字段
            String key = annotation.key();

            if (!ObjectUtils.isEmpty(key)) {
                try {
                    Field keyField = target.getClass().getDeclaredField(key);
                    keyField.setAccessible(true);
                    // 通过反射获取 target.type 的值
                    rawValue = keyField.get(target);
                } catch (Exception e) {
                    throw new RuntimeException("SmartTranslate 未找到字段: " + key, e);
                }
            }
            //根据指定字段值对比需要翻译的数据
            if (Objects.equals(rawValue.toString(), item.value())) {
                //获取最终翻译结果
                return item.label();
            }

        }
        return rawValue;
    }
}


